package eyer.utils;

import java.lang.management.ManagementFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import eyer.jvm.JVMGC;
import eyer.jvm.JVMInfo;
import eyer.jvm.JVMMemory;
import eyer.jvm.JVMThread;

public class JMXUtils {
    private static MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();

    public static final String PRE = "eyer.jshot:type=";

    public static void regMbean() throws Exception {
        unregMbean();
        ObjectName jvmInfoName = new ObjectName(PRE + "JVMInfo");
        ObjectName jvmMemoryName = new ObjectName(PRE + "JVMMemory");
        ObjectName jvmGCName = new ObjectName(PRE + "JVMGC");
        ObjectName jvmThreadName = new ObjectName(PRE + "JVMThread");
        mbeanServer.registerMBean(JVMInfo.getInstance(), jvmInfoName);
        mbeanServer.registerMBean(JVMMemory.getInstance(), jvmMemoryName);
        mbeanServer.registerMBean(JVMGC.getInstance(), jvmGCName);
        mbeanServer.registerMBean(JVMThread.getInstance(), jvmThreadName);
    }

    public static void unregMbean() throws Exception {
        ObjectName jvmInfoName = new ObjectName(PRE + "JVMInfo");
        ObjectName jvmMemoryName = new ObjectName(PRE + "JVMMemory");
        ObjectName jvmGCName = new ObjectName(PRE + "JVMGC");
        ObjectName jvmThreadName = new ObjectName(PRE + "JVMThread");

        List<ObjectName> objectNameList = new ArrayList<ObjectName>();

        objectNameList.add(jvmInfoName);
        objectNameList.add(jvmMemoryName);
        objectNameList.add(jvmGCName);
        objectNameList.add(jvmThreadName);
        for (ObjectName objectName : objectNameList) {
            if (mbeanServer.isRegistered(objectName)) {
                mbeanServer.unregisterMBean(objectName);
            }
        }
    }

    /*
-Dcom.sun.management.jmxremote 
-Dcom.sun.management.jmxremote.port="8989" 
-Dcom.sun.management.jmxremote.ssl=false 
-Dcom.sun.management.jmxremote.authenticate=false
     */
    public static void main(String[] args) {
        try {
            JMXUtils.regMbean();

            int cc = 0;
            int maxCount = 100;
            while (true) {
                Thread.sleep(1000 * 2);
                cc++;

                if (cc % 2 == 0) {
                    List<Object> ll = new ArrayList<Object>(100);
                    int total = new Random().nextInt(1000);
                    for (int i = 0; i < total; i++) {
                        ll.add(new Object());
                    }
                }

                System.out.println("loop " + cc);

                if (cc > maxCount)
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
